﻿using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using TaskCaller.Models;
using TaskCaller.Repositories;
using TaskCaller.Services;

namespace TaskCaller
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            //services.Configure<CookiePolicyOptions>(options =>
            //{
            //    options.CheckConsentNeeded = context => false; //false可以直接使用cookie
            //    options.MinimumSameSitePolicy = SameSiteMode.None;
            //});


            services.AddDistributedMemoryCache();

            services.AddSession(options =>
            {
                // Set a short timeout for easy testing.
                options.Cookie.HttpOnly = true;
                // Make the session cookie essential
                options.Cookie.IsEssential = true;
            });

            // 注册仓储
            services.AddTaskCallerRepository(Configuration);

            //添加TaskerCaller服务
            services.AddTaskCaller(Configuration);

            services.AddControllersWithViews(options =>
            {
                options.Filters.Add<MyExceptionFilterAttribute>();
            });

            //分页帮助标记需要访问ActionContextAccessor
            services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.EnvironmentName == "Development")
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            //app.UseHttpsRedirection();

            app.UseStaticFiles();

            //app.UseCookiePolicy();
            app.UseSession();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }


        public static bool IsLogin(HttpContext context)
        {

            if (context.Session.TryGetValue("auth", out byte[] buffer))
            {
                if (Encoding.UTF8.GetString(buffer) == "1")
                {
                    return true;
                }
            }
            return false;
        }
    }
}